home *** CD-ROM | disk | FTP | other *** search
/ Delphi Magazine Collection 2001 / Delphi Magazine Collection 20001 (2001).iso / DISKS / Issue24 / ntserv / Logging.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1997-07-04  |  2.1 KB  |  94 lines

  1. unit Logging;
  2.  
  3. interface
  4.  
  5. { A simple logging device to write info to a text file then optionally display }
  6. { the log (for non-console apps), using notepad, when the program terminates.  }
  7.  
  8. procedure Log(const Msg: string);
  9. procedure LogFmt(const Msg: string; const Args: array of const);
  10.  
  11. implementation
  12.  
  13. uses Windows, SysUtils, Classes, Controls, Forms;
  14.  
  15. type
  16.   TLogger = class
  17.   private
  18.     FStream: TFileStream;
  19.   public
  20.     constructor Create;
  21.     destructor Destroy; override;
  22.     class function LogFileName: string;
  23.     procedure WriteToStream(const Text: string);
  24.     procedure WriteToStreamLn(const Text: string);
  25.   end;
  26.  
  27. const
  28.   LogStream: TLogger = nil;
  29.  
  30. constructor TLogger.Create;
  31. begin
  32.   FStream := TFileStream.Create(LogFileName,fmCreate);
  33. end;
  34.  
  35. destructor TLogger.Destroy;
  36. begin
  37.   FStream.Free;
  38.   inherited Destroy;
  39. end;
  40.  
  41. class function TLogger.LogFileName: string;
  42. begin
  43.   Result := Concat(ExtractFilePath(Application.ExeName),'LOG.TXT');
  44. end;
  45.  
  46. procedure TLogger.WriteToStream(const Text: string);
  47. begin
  48.   FStream.Write(Text[1],Length(Text));
  49. end;
  50.  
  51. procedure TLogger.WriteToStreamLn(const Text: string);
  52. begin
  53.   WriteToStream(Text+#13#10);
  54. end;
  55.  
  56. procedure Log(const Msg: string);
  57. begin
  58.   if not Assigned(LogStream) then
  59.     LogStream := TLogger.Create;
  60.   LogStream.WriteToStreamLn(Msg);
  61. end;
  62.  
  63. procedure LogFmt(const Msg: string; const Args: array of const);
  64. begin
  65.   Log(Format(Msg,Args));
  66. end;
  67.  
  68. var
  69.   ExitSave: Pointer;
  70.  
  71. {==============================================================================}
  72. procedure UnitExitProc; Far;
  73. var
  74.   wrkarea: array[0..255] of char;
  75.  
  76. begin
  77.   ExitProc:=ExitSave;
  78.   if Assigned(LogStream) then
  79.     begin
  80.       LogStream.Free;
  81.       if not IsConsole then
  82.         if MessageBox(0,'Show log file?','Log results',MB_YESNO) = mrYes then
  83.           begin
  84.             StrPCopy(Wrkarea,'notepad ' + LogStream.LogFileName);
  85.             WinExec(wrkarea,SW_SHOWMAXIMIZED);
  86.           end;
  87.     end;
  88. end;
  89. {==============================================================================}
  90. Begin
  91.   ExitSave:=ExitProc;
  92.   ExitProc:=@UnitExitProc;
  93. end.
  94.